package tasks;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

import core.Bencoder;

public class CreateTorrent implements Runnable {

	private File file;
	private String tracker;
	private int pieceLength;
	private String author;
	private String comment;

	public CreateTorrent (File file,int pieceLength, String track, String author, String comment){

		this.file = file;
		this.pieceLength = pieceLength;
		this.tracker = track;
		this.author = author;
		this.comment = comment;

	}
	@Override
	public void run() {
		HashMap hm = new HashMap<Object, Object>();
		HashMap info = new HashMap<Object, Object>();
		hm.put("announce", this.tracker);
		info.put("piece length", pieceLength);
		info.put("name", file.getName());
		info.put("length", file.length());
		info.put("createdBy", this.author);
		info.put("comment", this.comment);

		int nbPieces = (int) Math.ceil((double)file.length()/pieceLength);

		try {
			FileInputStream fin = new FileInputStream(file);
			byte[] buffer = new byte[pieceLength];
			byte[] pieces = new byte[20*nbPieces];

			MessageDigest cript;

			int cpt = 1;
			int pointeur = 0;

			while(fin.read(buffer) != -1) {
				System.out.println("nbpiece:"+cpt);

				cript = MessageDigest.getInstance("SHA-1");
				cript.reset();
				cript.update(buffer);				

				System.arraycopy(cript.digest(), 0, pieces, pointeur, 20); 

				pointeur += 20;
				cpt++;
			}

			info.put("pieces", pieces);

			hm.put("info", info);
		} catch (FileNotFoundException e3) {
			e3.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e2) {
			e2.printStackTrace();
		} 

		FileOutputStream os;

		try {
			os = new FileOutputStream(file.getName()+".torrent");
			Bencoder.bencode(hm, os);

		} catch (FileNotFoundException e1) {
			e1.printStackTrace();				
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
